package com.xiaoxie.controller;


import com.xiaoxie.DTO.UserDTO;
import com.xiaoxie.entity.BaseContext;
import com.xiaoxie.entity.JwtUtil;
import com.xiaoxie.entity.Result;
import com.xiaoxie.entity.User;
import com.xiaoxie.service.IUserService;
import com.xiaoxie.service.IWord_tbService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 小谢
 * @since 2023-10-13
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IWord_tbService word_tbService;
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    /**
     * 用户学习状态更新
     *
     */
    @PutMapping
    public Result<String> updateFinish() {
        boolean finish = userService.updateFinish(BaseContext.getCurrentAccount());
        Result<String> success = Result.success();
        if (finish){
            success.setCode(200);
            success.setMsg("学习完成");
        }
        return success;
    }

    @PostMapping("/admin/login")
    public Result<UserDTO> login(@RequestBody UserDTO userDTO){
        User user=userService.Login(userDTO);
        log.info("登录{}", userDTO);
        if (user!= null){
            user.setUserpwd("*********");
            Map<String, Object> claims = new HashMap<>();
            claims.put("account",user.getUserAccount());
            String jwt = JwtUtil.createJWT("xiaoxie", 7200000, claims);
            UserDTO ResultUser = new UserDTO();
            BeanUtils.copyProperties(user,ResultUser);
            ResultUser.setToken(jwt);
            log.info("登录{}", ResultUser);
            userService.initial(user);
            return Result.success(ResultUser);
        }
        return Result.error("登录失败");
    }
    @PostMapping("/enroll")
    public Result<String> enrollUser(@RequestParam("account") String account, @RequestParam("password") String password) {
        boolean b = userService.insertUser(account, password);
        return b?Result.error("注册成功"):Result.error("注册失败,账号已存在");
    }
}

